﻿"use strict"

var chatHub = new signalR.HubConnectionBuilder().withUrl("/chatHub").build();
chatHub.on("ReceiveMessage", function (user, message) {
    var li = $("<li ></li>");
    var currentTime = new Date().toLocaleTimeString(); // 获取当前时间
    var text = `<fieldset class="layui-elem-field layui-field-title"><legend>` + user + `</legend></fieldset> <div class="layui-btn-radius layui-panel block-div">` + message.replace(/\n/g, "<br>") + " <span class='layui-btn-primary layui-btn-radius layui-btn-xs' style=' margin-left:20px;'>" + currentTime + "</span></div>";

    // 将text添加到li元素中
    li.html(text);
    $("#ul").append(li);
    //console.log(user + ": " + message);
});
chatHub.start().then(function () {
    document.getElementById("send").disabled = false;
}).catch(function (err) {
    return console.error(err.toString());
});

$("#send").on("click", function () {
    var msg = $("#msg").val();
    var user = '@LoginMode.username';
    var currentTime = new Date().toLocaleTimeString();
    var mode = {
        Name: user,
        Time: currentTime,
        Text: msg
    }
    axios.post("/Chat/Add", mode)
        .then(d => {
            console.log(d.data.Msg); // 响应数据
        })
        .catch(error => {
            console.error(error); // 错误信息
        });

    chatHub.invoke("Send", user, msg);
    $("#msg").val("");
    var chatMessages = $("#ul");
    var scrollHeight = chatMessages.prop("scrollHeight");
    chatMessages.animate({ scrollTop: scrollHeight }, 500);
})

document.getElementById("msg").addEventListener("keydown", function (event) {
    if (event.keyCode === 13) { // 按下回车键的键码是13
        event.preventDefault(); // 阻止默认的回车行为
        document.getElementById("send").click(); // 模拟点击发送按钮
    }
});
